﻿using EMall.Application;
using EMall.Query;
using EMall.Uow;
using Microsoft.EntityFrameworkCore;

namespace EMall.ProductService.Brands
{
    public class BrandAppService : ApplicationService, IBrandAppService
    {
        private readonly IBrandRepository _brandRepository;
        private readonly BrandManager _brandManager;
        public BrandAppService(
            IBrandRepository brandRepository,
            BrandManager brandManager)
        {
            _brandRepository = brandRepository;
            _brandManager = brandManager;
        }
        [UnitOfWork]
        public async Task CreateAsync(CreateBrandDto input)
        {
            var name = await _brandManager.CheckNameExistsAsync(input.Name);
            var brand = new Brand(name, input.LogoUrl);
            await _brandRepository.AddAsync(brand);
        }
        [UnitOfWork]
        public async Task UpdateAsync(UpdateBrandDto input)
        {
            var brand = await _brandRepository.GetAsync(input.Id);
            var newName = await _brandManager.CheckNewNameExistsAsync(brand, input.Name);
            brand.Update(input.Name, input.LogoUrl);
        }
        [UnitOfWork]
        public async Task DeleteAsync(DeleteBrandDto input)
        {
            var product = await _brandRepository.GetAsync(input.Id);
            await _brandRepository.RemoveAsync(product);
        }
        public async Task<BrandDto> GetAsync(int id)
        {
            var brand = await QueryService.GetAsync<Brand, int>(id);
            return Mapper.Map<BrandDto>(brand);
        }
        public async Task<IEnumerable<BrandListDto>> GetListAsync(GetBrandListQueryDto input)
        {
            var data = await QueryService.GetQueryable<Brand>()
               .Sorting(input.Sorting)
               .ToListAsync();
            return Mapper.Map<List<Brand>, List<BrandListDto>>(data);
        }
        public async Task<IPagedList<BrandListDto>> GetPagedListAsync(GetBrandListPagingAndSortingQueryDto input)
        {
            var data = await QueryService.GetQueryable<Brand>()
               .Sorting(input.Sorting)
               .ToPagedListAsync(input.PageIndex, input.PageSize);
            return Mapper.Map<Brand, BrandListDto>(data);
        }
    }
}